<template>
  <a-modal
    title="新建角色"
    :width="800"
    :visible="visible"
    :confirmLoading="confirmLoading"
    :maskClosable="false"
    @ok="handleSubmit"
    @cancel="handleCancel"
  >
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">

        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="角色名称">
          <a-input placeholder="角色名称"
                   v-decorator="[ 'roleName', {rules: [{ required: true, message: '请输入。。。' }]}]"
          ></a-input>
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="角色描述">
          <a-input placeholder="角色描述"
                   v-decorator="[ 'description', {rules: [{ required: true, message: '请输入。。。' }]}]"
          ></a-input>
        </a-form-item>

        <a-divider/>

        <div v-for="(item, index) in parentMenus" :key="index">
          <a-form-item
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            :label="item.menuName"
          >
            <a-row :gutter="8" v-for="(permission, index) in item.children" :key="index">
              <a-col :span="4">
                {{ permission.menuName }}
              </a-col>
              <a-col :span="20">
                <a-checkbox
                  :indeterminate="permission.indeterminate"
                  :checked="permission.checkedAll"
                  @change="onChangeCheckAll($event, permission)">全选
                </a-checkbox>
                <a-checkbox-group :options="permission.actionsOptions" v-model="permission.actions" @change="onChangeCheck(permission)" />
              </a-col>
            </a-row>
          </a-form-item>
        </div>

      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
  import pick from 'lodash.pick'
  import { selectByRoleId, selectAll } from '@/api/system/menu'
  import { saveOrUpdate } from '@/api/system/role'

export default {
  data () {
    return {
      id: null,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      visible: false,
      confirmLoading: false,
      isDisabled: false,
      parentMenus: [],

      form: this.$form.createForm(this)
    }
  },
  created() {
    this.loadPermissions()
  },
  methods: {
    add () {
      this.visible = true
      this.parentMenus.forEach(item => {
        item.children.forEach(permission => {
          permission.actions = []
        })
      })
    },
    edit (record) {
      this.id = record.id
      this.visible = true
      this.isDisabled = true

      selectByRoleId(this.id).then(res =>{
        const result = res.data
        //有权限表，处理勾选
        if (result && this.parentMenus) {
          // 先处理要勾选的权限结构
          const permissionsAction = {}
          result.forEach(permission => {
            permissionsAction[permission.id] = permission.actions
          })
          // 把权限表遍历一遍，设定要勾选的权限 action

          this.parentMenus.forEach(item => {
            item.children.forEach(permission => {
              permission.actions = permissionsAction[permission.id] || []
            })
          })
        }
      })

      const { form: { setFieldsValue } } = this
      this.$nextTick(() => {
        setFieldsValue(pick(record, ['roleName', 'description', 'type']))
      })
    },
    handleSubmit () {
      const { form: { validateFields } } = this
      this.confirmLoading = true
      validateFields((errors, values) => {
        if (!errors) {
          values.id = this.id
          values.menuList = this.parentMenus
          saveOrUpdate(values).then((res) => {
            this.confirmLoading = false
            if (res.code === 200) {
              this.handleCancel()
              this.$emit('ok')
            }
          })
        } else {
          this.confirmLoading = false
        }
      })
    },
    handleCancel () {
      this.visible = false
      this.form.resetFields()
      this.id = null
    },
    loadPermissions () {
      const that = this
      selectAll().then(res => {
        const result = res.data
        that.parentMenus = result.map(item => {
          item.children.map(permission => {
            const options = permission.buttonList
            permission.checkedAll = false
            permission.actions = []
            permission.indeterminate = false
            permission.actionsOptions = options.map(option => {
              return {
                label: option.menuName,
                value: option.keySign
              }
            })
            return permission
          })
          return item
        })
      })
    },
    onChangeCheck (permission) {
      permission.indeterminate = !!permission.actions.length && (permission.actions.length < permission.actionsOptions.length)
      permission.checkedAll = permission.actions.length === permission.actionsOptions.length
    },
    onChangeCheckAll (e, permission) {
      Object.assign(permission, {
        actions: e.target.checked ? permission.actionsOptions.map(obj => obj.value) : [],
        indeterminate: false,
        checkedAll: e.target.checked
      })
    },
  }
}
</script>
